// pages/detail-songs/index.js
import {userStore,playerStore} from '../../store/index'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
const db = wx.cloud.database()
Page({
  data: {
    songInfo:[],
    isLogin:false,
    userName:""
  },

  onLoad: function (options) {
    const id = options.id
    db.collection('recommendSongMenu').doc(id).get()
    .then(res=>{
      this.setData({songInfo:res.data})
    })
  },

  handleSongItemClick:function(event){
    const index = event.currentTarget.dataset.index
    playerStore.setState("playListSongs",this.data.songInfo.collectionList.songInfo)
    playerStore.setState("playListIndex",index)
  },

  handleCollectClick:function(){
    userStore.onState("isLogin",(value)=>{
      console.log(value)
      this.setData({isLogin:value})
    })
    userStore.onState("username",(value)=>{
      console.log(value)
      this.setData({userName:value})
    })
    console.log(this.data.isLogin);
    if(this.data.isLogin === 'false'){
      Dialog.confirm({
        title:'',
        message: '您还未登录，是否前往登录？',
      })
        .then(() => {
          wx.navigateTo({
            url: '../login/index',
          })
          
        })
        .catch(() => {
          console.log('取消')
        });
    }
    else if(this.data.isLogin === 'true'){
      Dialog.confirm({
        title:'',
        message: '确认要收藏此歌单吗？',
      })
      .then(() => {       
          var id = this.data.songInfo.id
          db.collection('collectionMenu')
          .where({
            id:id,
            userName:this.data.userName
          })
          .get()
          .then(res=>{
            console.log(res);
            if(res.data.length == 0){
              //没有歌单添加歌单
              console.log();
              console.log('没有这个歌单');
              db.collection('collectionMenu').add({
                data:{
                  userName:this.data.userName,
                  id:this.data.songInfo.id,
                  coverImgUrl:this.data.songInfo.coverImgUrl,
                  name:this.data.songInfo.name,
                  collectionList:this.data.songInfo.collectionList
                }
              })

             Toast('收藏成功')
            }
            else if(res.data.length !== 0){
              Toast('已经存在该歌单');
            }
          })

  
        })
        .catch(() => {
          console.log('取消')
        });
    }
   
    
  },

})